﻿using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.Welfare.Interfaces.WelfareBill;
using PARK.Welfare.Entitys;
using PARK.Common.Core.Manager;
using PARK.Welfare.Entitys.Dto.WelfareBill;
using PARK.ClayObject;
using PARK.Common.Model.NPOI;
using PARK.Common.Configuration;
using PARK.DataEncryption;
using PARK.Welfare.Interfaces.WelfareDetail;
using PARK.Welfare.Entitys.Dto.WelfareDetail;
using System.Text;

namespace PARK.Welfare.WelfareBill
{
    /// <summary>
    /// 发放统计服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Welfare", Name = "StatisReport", Order = 200)]
    [Route("api/welfare/[controller]")]
    public class WelfareStatisService : IWelfareDetailService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<WelfareDetailEntity> _welfareDetailRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="WelfareBillService"/>类型的新实例
        /// </summary>
        public WelfareStatisService(
            ISqlSugarRepository<WelfareDetailEntity> welfareDetaRepository,
            IUserManager userManager)
        {
            _welfareDetailRepository = welfareDetaRepository;
            _db = _welfareDetailRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取福利发放统计
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<WelfareDetailEntity>().FirstAsync(p => p.BillId == id);
            var output = entity.Adapt<WelfareDetailInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取福利发放统计列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] WelfareDetailListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var sidx = input.sidx == null ? "departName" : input.sidx;
            //选中公司查询全部
            if (input.departId == userInfo.companyId)
            {
                input.departId = null;
            }
            //发放时间
            List<string> queryDetectTime = input.inputBillDate != null ? input.inputBillDate.Split(',').ToObeject<List<string>>() : null;
            DateTime? startDetectdate = queryDetectTime != null ? Ext.GetDateTime(queryDetectTime.First()) : null;
            DateTime? endDetectdate = queryDetectTime != null ? Ext.GetDateTime(queryDetectTime.Last()) : null;

            if (userInfo != null)
            {
                StringBuilder dbSql = new StringBuilder("select  departid,departname,sum(Amount) Amount,count(0) as times,sum(ConSumAmt) ConSumAmt from welfare_detail where ISNULL(IsAccounted, 0) = 1 ");
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    dbSql.AppendFormat(" and (JobNo like '%{0}%' or ReallName like '%{0}%' or CardNo like '%{0}%' or BillCode like '%{0}%')", input.keyword);
                }
                if (!string.IsNullOrEmpty(input.departId))
                {
                    dbSql.AppendFormat(" and departid= '{0}'", input.departId);
                }
                if (input.inputBillDate != null)
                {
                    dbSql.AppendFormat(" and billDate>='{0}'", new DateTime(startDetectdate.ToDate().Year, startDetectdate.ToDate().Month, startDetectdate.ToDate().Day, 0, 0, 0).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (input.inputBillDate != null)
                {
                    dbSql.AppendFormat(" and billDate<='{0}'", new DateTime(startDetectdate.ToDate().Year, startDetectdate.ToDate().Month, startDetectdate.ToDate().Day, 23, 59, 59).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                dbSql.AppendFormat(" and CompanyId='{0}'", userInfo.companyId);
                dbSql.AppendFormat(" group by departid,departname ");
                var data = _db.SqlQueryable<WelfareDetailListOutput>(dbSql.ToString()).Select(it => new WelfareDetailListOutput
                {
                    departId = it.departId,
                    departName = it.departName,
                    amount = it.amount,
                    times = it.times,
                }).ToList();
                return data;
            }
            else
            {
                return null;
            }
        }


        #region 导出Excel
        /// <summary>
        /// 获取发放统计无分页列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] WelfareDetailListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var sidx = input.sidx == null ? "departName" : input.sidx;
            //选中公司查询全部
            if (input.departId == "96240625-934F-490B-8AA6-0BC775B18468")
            {
                input.departId = null;
            }
            //发放时间
            List<string> queryDetectTime = input.inputBillDate != null ? input.inputBillDate.Split(',').ToObeject<List<string>>() : null;
            DateTime? startDetectdate = queryDetectTime != null ? Ext.GetDateTime(queryDetectTime.First()) : null;
            DateTime? endDetectdate = queryDetectTime != null ? Ext.GetDateTime(queryDetectTime.Last()) : null;
            if (userInfo != null)
            {
                StringBuilder dbSql = new StringBuilder("select departid,departname,sum(Amount) Amount,count(0) as times,sum(ConSumAmt) ConSumAmt from welfare_detail where ISNULL(IsAccounted, 0) = 1 ");
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    dbSql.AppendFormat(" and (JobNo like '%{0}%' or ReallName like '%{0}%' or CardNo like '%{0}%' or BillCode like '%{0}%')", input.keyword);
                }
                if (!string.IsNullOrEmpty(input.departId))
                {
                    dbSql.AppendFormat(" and departid= '{0}'", input.departId);
                }
                if (input.inputBillDate != null)
                {
                    dbSql.AppendFormat(" and billDate>='{0}'", new DateTime(startDetectdate.ToDate().Year, startDetectdate.ToDate().Month, startDetectdate.ToDate().Day, 0, 0, 0).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (input.inputBillDate != null)
                {
                    dbSql.AppendFormat(" and billDate<='{0}'", new DateTime(startDetectdate.ToDate().Year, startDetectdate.ToDate().Month, startDetectdate.ToDate().Day, 23, 59, 59).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                dbSql.AppendFormat(" and CompanyId='{0}'", userInfo.companyId);
                dbSql.AppendFormat(" group by departid,departname ");
                var data = _db.SqlQueryable<WelfareDetailListOutput>(dbSql.ToString()).Select(it => new WelfareDetailListOutput
                {
                    departId = it.departId,
                    departName = it.departName,
                    amount = it.amount,
                    times = it.times,
                }).ToList();
                return data;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 导出发放记录
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] WelfareDetailListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<WelfareDetailListOutput>();
            var exportDataNew = new List<WelfareDetailListOutput>();

            var entity = input.Adapt<WelfareDetailEntity>();

            if (input.dataType == 0)
            {
                exportData = await this.GetNoPagingList(input);
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }

            foreach (WelfareDetailListOutput item in exportData)
            {
                exportDataNew.Add(item);
            }

            List<ParamsModel> paramList = "[{\"value\":\"部门\",\"field\":\"departName\"},{\"value\":\"发放人次\",\"field\":\"times\"},{\"value\":\"发放金额\",\"field\":\"amount\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = userInfo.organizeName+"_" + "福利发放统计.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }


            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<WelfareDetailListOutput>.Export(exportDataNew, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "api/file/Download?encryption=" + DESCEncryption.Encrypt(fileName, "JNPF") //"wwwroot/Template/TemporaryFile/" + excelconfig.FileName //
            };
            return output;




        }
        #endregion
    }
}